#include "LppgmProtocol.h"
#include <util/crc16.h>

void SendACK(int dest,int src)
{
uint8_t b[8] = {STX, dest, src, ACK, FUNC_READ, EOT, 0x00, 0x00};

uint16_t crc;

crc = 0;
for(int8_t i = 0; i < 6; i++)
crc = _crc_ccitt_update(crc, b[i]);

b[6] = byte(crc);
b[7] = byte(crc >> 8); // MSB

PrintHex8(b,8);
Serial.println();
}
void SendNAK(int dest,int src)
{
	uint8_t b[8] = {STX, dest, src, NAK, FUNC_READ, EOT, 0x00, 0x00};

	uint16_t crc;

	crc = 0;
	for(int8_t i = 0; i < 6; i++)
	crc = _crc_ccitt_update(crc, b[i]);

	b[6] = byte(crc);
	b[7] = byte(crc >> 8); // MSB

	PrintHex8(b,8);
	Serial.println();
}
void SendBarcode(int dest, int src,uint16_t qc_id, uint32_t barcode,uint8_t he_type, uint16_t label_no, uint8_t order_type)
{
	uint8_t b[18] {
		STX, 
		dest, 
		src, 
		FUNC_BARCODE, 
		FUNC_READ,
		byte(qc_id),
		byte(qc_id >> 8),
		byte(barcode),
		byte(barcode>>8),
		byte(barcode>>16),
		byte(barcode>>24), // MSB
		byte(he_type),
		byte(label_no),		
		byte(label_no>>8), //MSB
		byte(order_type),
		EOT, 
		0x00, 
		0x00};
	
	uint16_t crc;
	
	crc = 0;
	for(int8_t i = 0; i < 16; i++)
	crc = _crc_ccitt_update(crc, b[i]);

	b[16] = byte(crc);
	b[17] = byte(crc >> 8); // MSB

	PrintHex8(b,18);
	Serial.println();
}

void PrintHex8(uint8_t *data, uint8_t length) // prints 8-bit data in hex with leading zeroes
{
	char tmp[16];
	for (int i=0; i<length; i++) 
	{
		sprintf(tmp, "%.2X",data[i]);
		Serial.print(tmp); 
		if(i < (length -1))
		 Serial.print("-");
	}
}

void PrintHex16(uint16_t *data, uint8_t length) // prints 16-bit data in hex with leading zeroes
{
	char tmp[16];
	for (int i=0; i<length; i++)
	{
		sprintf(tmp, "%.4X",data[i]);
		Serial.print(tmp); Serial.print("-");
	}
}